/*
 * File: layer0.cpp - contains the implementation of layer0 class
 * Author: Sam Tran (tpmsam@yahoo.com), UHCL, April 2006
 */

#include "layer0.h"

void layer0::initialize()
{
}


void layer0::activity()
{
	// main loop
	while(1)
	{
		cMessage * msg = receive();

		switch (msg->kind())
		{

		case M_NODE:					// message from another node
			msg->setKind(M_LOWHIGH);
			send(msg,"uppergate_out");
			break;


		case M_HIGHLOW:					// message from a higher layer
			{
				msg->setKind(M_NODE);
        if(strcmp(msg->name(),"SENSING_DATA")==0)
        	{
             if(OCCUPATION==2)
            	{
        		    send(msg,"lowergate_out",FATHER);
        	    }
             else if(OCCUPATION==1) 
        	    {
        		    send(msg,"lowergate_out",104);
        	    }
        	  }
        else if(strcmp(msg->name(),"INVITATION")==0)
        	{ 
				 //duplicate the message and send it through all the gates
				     for (int i=0;i < CNNCTVTY;i++)
				     {
				      	cGate *tmpgate = parentModule()->gate("out",i);
					
				      	if (tmpgate==NULL)
						    continue;
					   // if gate is connected, send a message through it
					      if (tmpgate->toGate()!=NULL)
					      {
						     cMessage *tmpmsg = new cMessage(*msg);
					        send(tmpmsg,"lowergate_out",i);
				       	}

				      }
				    }
 
				// delete original message
				else
				delete msg;
			}
			break;

			
		default:						// unknown message received - bug!. 
			ev << "layer0::activity() error: unknow message received\n";
			endSimulation();
		}
	}
}
